package org.phoenix.mall.admin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.phoenix.mall.admin.common.pojo.bo.LoginBO;
import org.phoenix.mall.admin.common.pojo.bo.UserBO;
import org.phoenix.mall.admin.common.pojo.vo.TokenVO;
import org.phoenix.mall.admin.common.utils.AuthUtil;
import org.phoenix.mall.admin.common.utils.PhoenixResponseJSON;
import org.phoenix.mall.admin.config.annotations.AuthIgnore;
import org.phoenix.mall.admin.config.annotations.AuthRequired;
import org.phoenix.mall.admin.pojo.User;
import org.phoenix.mall.admin.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.UUID;

@RestController
@RequestMapping("passport")
@Api(value = "管理员登录", tags = {"管理员登陆相关的API"})
public class PassportController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "用户名是否存在", notes = "用户名是否存在", httpMethod = "GET")
    @GetMapping("/usernameIsExsit")
    public PhoenixResponseJSON usernameIsExsit(
            @ApiParam(name = "username", value = "用户名")
            @RequestParam String username) {

        if (StringUtils.isBlank(username)) {
            return PhoenixResponseJSON.errorMsg("用户名不能为空！");
        }

        if (!"admin".equals(username)) {
            return PhoenixResponseJSON.errorMsg("用户名不存在！");
        }
        return PhoenixResponseJSON.ok();
    }

    @ApiOperation(value = "用户登陆", notes = "用户登陆", httpMethod = "POST")
    @PostMapping("/login")
    public PhoenixResponseJSON login(@RequestBody LoginBO loginBO) {
        String username = loginBO.getUsername();
        String password = loginBO.getPassword();

        // 0. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)) {
            return PhoenixResponseJSON.errorMsg("用户名或密码不能为空");
        }

        User user = userService.getByUsername(username);
        if (user == null || !user.getPassword().equals(password)){
            return PhoenixResponseJSON.errorMsg("用户名，密码不正确！");
        }

        String token = AuthUtil.getToken(user.getId().toString(),user.getPassword());
        TokenVO tokenVO = new TokenVO();
        tokenVO.setToken(token);

        return PhoenixResponseJSON.ok(tokenVO);
    }

}
